package com.duowan.cms.common.util;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

import com.duowan.cms.common.webapp.property.ExtendedPropertyPlaceholderConfigurer.PropertiesHolder;


/**
 * 邮件发送工具类
 */
public class MailUtil {
    private static final Logger logger = Logger.getLogger(MailUtil.class);

    public static void sendHtmlEmail(final String mailTo, final String title, final String content) throws Exception {
        String mailHost = PropertiesHolder.get("mail_host", "mail.yy.com");
        String account = PropertiesHolder.get("mail_account", "cms@yy.com");
        String pwd = PropertiesHolder.get("mail_pwd", "!@#duowancms");
        
        sendHtmlEmail(mailHost, account, pwd, mailTo, title, content);
    }
    
    public static void sendHtmlEmail(String mailHost, String account, String pwd, final String mailTo, final String title, final String content) throws Exception {
        
        if(StringUtil.hasOneEmpty(mailHost, account, pwd)){
            logger.error("the [mailHost|account|pwd] is empyt.can not send mail.");
            throw new Exception("the [mailHost|account|pwd] is empyt.can not send mail.");
        }
        
        if (StringUtil.hasOneEmpty(mailTo, title, content)) {
            logger.error("the [mail|title|content] is empyt.can not send mail.");
            throw new Exception("the [mail|title|content] is empyt.can not send mail.");
        }
        HtmlEmail email = new HtmlEmail();
        //String mailHost = PropertiesHolder.get("mail_host", "mail.yy.com");
        email.setHostName(mailHost);
        // email.setHostName("mail.duowan.com");
        // email.setTLS(true); // 是否TLS校验，，某些邮箱需要TLS安全校验
        // email.setSSL(true);
        //String account = PropertiesHolder.get("mail_account", "cms@yy.com");
        //String pwd = PropertiesHolder.get("mail_pwd", "!@#duowancms");
        email.setAuthenticator(new DefaultAuthenticator(account, pwd));
        email.setCharset("GB2312");
        email.addTo(mailTo);
        email.setFrom(account);
        email.setSubject(title);
        email.setHtmlMsg(content);
        email.send();
    }
    

    public static void main(String[] args) throws Exception {
        MailUtil.sendHtmlEmail("yangzhuangqiu@yy.com", "myJAVAMAIL2", "<font color='red'>test content不要回复</font>");
    }
}
